package autohotkeyide.hightlighter;

/**
 * @author sad
 */
public class WordParser {

    private char[] buffer;
    private int currentPos = 0;
    private int lastWordPosition=0;
    
    public void setText(String text) {
        buffer = text.toCharArray();
    }

    public String getNextWord() {
        try {
            while (true) {
                char c = getCurrentChar();
                if ( isCharacter(c)) {
                    lastWordPosition=getCurrentPosition()-1;
                    return readIdentifier(c);
                }
            }
        } catch (EndOfFileException ex) {
            return null;
        }
    }

    public int getCurrentPosition(){
        return currentPos;
    }

    public int getLastWordPosition() {
        return lastWordPosition;
    }
    
    private boolean isCharacter(char c){
        return Character.isJavaIdentifierPart(c) || c=='#';
    }
    
    private String readIdentifier(char firstSymbol) {
        StringBuilder sb = new StringBuilder(30);
        sb.append(firstSymbol);
        while (true) {
            try {
                char c = getCurrentChar();
                if (isCharacter(c)) {
                    sb.append(c);
                } else {
                    break;
                }
            } catch (EndOfFileException ex) {
                break;
            }
        }
        return sb.toString();
    }

    private boolean isSpace(char c) {
        return Character.isSpaceChar(c) || c=='\t' || c=='\r' || c=='\n';
    }

    private void skipSpaces() {
        while (true) {
            char c = getCurrentChar();
            if (!isSpace(c)) {
                unread();
                break;
            }
        }
    }

    public char getCurrentChar() {
        if (currentPos >= buffer.length) {
            throw new EndOfFileException();
        }
        char c = buffer[currentPos];
        currentPos++;
        return c;
    }

    public void unread() {
        currentPos--;
    }

    static class EndOfFileException extends RuntimeException {
    }
}
